import { SharedMethodService } from './../../../@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import { EncodeRulesService } from './../../../@core/services/encoderRule/encode-rules.service';
import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig } from 'ng-devui';
import { ReviewFormDataComponent } from 'src/app/@shared/components/review-form-data/review-form-data.component';
@Component({
  selector: 'app-encoding-rules',
  templateUrl: './encoding-rules.component.html',
  styleUrls: ['./encoding-rules.component.scss']
})
export class EncodingRulesComponent {
  EncodingRules: any;//编码规则
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  }
  checkedIds = []
  pageSizeOptions = [10, 20, 30, 50, 100]
  msgs: { severity: any; summary: any; content: any; }[]
  config = {
    id: 'Add-Dirctoy-Type',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  filterType: string = ''
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent
  checkboxList = []
  allChecked = false
  halfChecked = false
  constructor(private EncodeRulesService: EncodeRulesService, private Router: Router, private dialogService: DialogService, private SharedMethodService: SharedMethodService) { }
  ngOnInit(): void {
    this.EncodeRulesService.getEncodingRules(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.EncodingRules = data.items;
      for (let rule of this.EncodingRules) {
        // 生成 code 属性
        rule.code = rule.items.map((item: { value: any; }) => item.value).join(rule.separator)
      }
      this.pager.total = data.totalCount;
    })//获取编码规则
  }
  dataTableOptions = {
    columns: [
      {
        field: 'showType',
        header: '单据类型',
        fieldType: 'text'
      },
      {
        field: 'type',
        header: '编码',
        fieldType: 'text'
      },
      {
        field: 'enabled',
        header: '状态',
        fieldType: 'boolean'
      }
    ]
  };//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field: 'caozuo',
      width: '150px'
    },
    {
      field: 'showType',
      width: '250px'
    },
    {
      field: 'type',
      width: '250px'
    },
    {
      field: 'enabled',
      width: '150px'
    }
  ];//表格宽度配置
  pageIndexChange($event: any) {
    this.filter();
  }//切换页码
  pageSizeChange($event: any) {
    this.filter();
  }//改变每页显示数量
  EnableCodeRule() {
    if (this.checkedIds) {
      this.EncodeRulesService.EnableCodeRules(this.checkedIds).subscribe((data: any) => {
        this.EncodeRulesService.getEncodingRules(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
          this.EncodingRules = data.items;
          this.CheckedRowsData = [];
          for (let rule of this.EncodingRules) {
            // 生成 code 属性
            rule.code = rule.items.map((item: { value: any; }) => item.value).join(rule.separator);
          }
          this.pager.total = data.totalCount;
        })//获取编码规则
      })
    }
  }//启用
  DisableCodeRule() {
    if (this.checkedIds) {
      this.EncodeRulesService.DisableCodeRule(this.checkedIds).subscribe((data: any) => {
        this.EncodeRulesService.getEncodingRules(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
          this.EncodingRules = data.items;
          this.CheckedRowsData = [];
          for (let rule of this.EncodingRules) {
            // 生成 code 属性
            rule.code = rule.items.map((item: { value: any; }) => item.value).join(rule.separator);
          }
          this.pager.total = data.totalCount;

        })//获取编码规则
      })
    }
  }//禁用
  DeleteEncodingRules(id: any, dialogtype?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该该编码规则？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.EncodeRulesService.DeleteEncodingRules(id).subscribe((data: any) => {
              this.showToast('success', '成功', '编码规则删除成功')
              results.modalInstance.hide();
              this.EncodeRulesService.getEncodingRules(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                this.EncodingRules = data.items;
                for (let rule of this.EncodingRules) {
                  // 生成 code 属性
                  rule.code = rule.items.map((item: { value: any; }) => item.value).join(rule.separator);
                }
                this.pager.total = data.totalCount;
              })//获取编码规则
            },(error: any) => {
              if (error.status === 404) {
                this.showToast('error', '错误', '网络连接错误');
              } else {
                this.showToast('error', '错误', error.error);
              }
            })
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//删除
  edit(id: any) {
    this.Router.navigate(['/pages/systemset/Edit-Encoding-Rules', id]);
  }//编辑
  filter() {
    this.EncodeRulesService.getEncodingRulesByType(this.filterType, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.EncodingRules = data.items;
      for (let rule of this.EncodingRules) {
        // 生成 code 属性
        rule.code = rule.items.map((item: { value: any; }) => item.value).join(rule.separator);

        // 检查是否在 CheckedRowsData 中
        if (this.CheckedRowsData.some((checkedItem: { id: any; }) => checkedItem.id === rule.id)) {
          rule.$checked = true;
        }
      }
      this.pager.total = data.totalCount;
    });
  }//筛选
  filter2() {
    this.pager.pageIndex = 1;
    this.EncodeRulesService.getEncodingRulesByType(this.filterType, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.EncodingRules = data.items;
      for (let rule of this.EncodingRules) {
        // 生成 code 属性
        rule.code = rule.items.map((item: { value: any; }) => item.value).join(rule.separator);

        // 检查是否在 CheckedRowsData 中
        if (this.CheckedRowsData.some((checkedItem: { id: any; }) => checkedItem.id === rule.id)) {
          rule.$checked = true;
        }
      }
      this.pager.total = data.totalCount;
    });
  }//筛选
  reset() {
    this.filterType = '';
    this.filter2();
  }//重置
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  cleared() {
    this.SharedMethodService.cleared(this.checkedIds, this.EncodingRules, this.datatable).subscribe((data: any) => {
      this.checkedIds = data;
      this.CheckedRowsData = [];
    })
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable);
    this.getCheckedRows();
  }//单选
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable, 'id').subscribe((data: any) => {
      this.checkedIds = data;
    })
    this.getCheckedRowsData();
  }//获取选中行
  getHeadCheckStatus($event: any) {
    if (!$event) {
      // 过滤掉所有 EncodingRules 中 id 相同的项
      this.CheckedRowsData = this.CheckedRowsData.filter((checkedItem: any) =>
        !this.EncodingRules.some((rule: any) => rule.id === checkedItem.id)
      );
    }
  }
  CheckedRowsData = [];//选中行数据
  getCheckedRowsData() {
    const rows = this.datatable.getCheckedRows();
    const checkedRows = rows.filter((item: any) => item.$checked);
    // 合并当前页面选中的行和之前选中的行
    const allCheckedRows = [...this.CheckedRowsData.filter((item: any) => !rows.includes(item)), ...checkedRows];
    // 去重，确保每个 id 只保留一个对象
    const uniqueCheckedRows = allCheckedRows.reduce((acc: any[], current: any) => {
      const x = acc.find(item => item.id === current.id);
      if (!x) {
        acc.push(current);
      }
      return acc;
    }, []);
    this.CheckedRowsData = uniqueCheckedRows;
  }
  reviewChecked(dialogtype?: string) {
    const results = this.dialogService.open({
      ...this.config,
      width: '900px',
      title: '已选数据',
      data: {
        tableData: this.CheckedRowsData,
        dataLength: this.CheckedRowsData.length,
        items: [
          { name: 'number', type: 'text' },
          { name: 'checkbox', type: 'checkbox' },
          { name: 'type', type: 'text' },
          { name: 'code', type: 'text' },
          { name: 'enabled', type: 'tag' }
        ],
        tableWidthConfig: this.tableWidthConfig,
        dataTableOptions: this.dataTableOptions,
      },
      content: ReviewFormDataComponent,
      dialogtype: dialogtype,

      onClose: () => {
        this.CheckedRowsData = results.modalContentInstance.displayTableData;
        const allIds = this.EncodingRules.map(rule => rule.id);
        const checkedIds = this.CheckedRowsData.map(item => item.id);

        const allExist = allIds.every(id => checkedIds.includes(id));
        const noneExist = allIds.every(id => !checkedIds.includes(id));
        if (allExist) {
        } else if (noneExist) {
          this.cleared()
        } else {
          this.datatable.setTableCheckStatus(
            {
              pageHalfChecked: true,
            }
          );
        }
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '关闭',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        }
      ],
    })
  }
  reviewCheckedData(dialogtype?: string) {
  }
  selectedRows: any[] = [];
  loadData() {
    this.EncodingRules.forEach(row => {
      if (this.isRowSelected(row)) {
        row.$checked = true;
      }
    });
  }
  onRowSelect(row: any, event: boolean) {
    if (!event) {
      this.CheckedRowsData = this.CheckedRowsData.filter((item: { id: any; }) => item.id !== row.id);
    }
  }
  // 检查行是否被选中
  isRowSelected(row: any): boolean {
    return this.selectedRows.includes(row);
  }
}

